package com.pku.smart.controller;

import com.alibaba.fastjson.JSON;
import com.pku.smart.constant.PayConstant;
import com.pku.smart.log.MyLog;
import com.pku.smart.service.SmartPayService;
import com.pku.smart.trade.service.IPaymentManagerService;
import com.pku.smart.trade.vopackage.VoReqRefund;
import com.pku.smart.trade.vopackage.VoResRefund;
import com.pku.smart.trade.vopackage.VoResTradePayment;
import com.pku.smart.vopackage.TradeResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/api")
public class PayRefundController {

    private static final MyLog _log = MyLog.getLog(PayRefundController.class);

    @Autowired
    SmartPayService smartPayService;

    @Autowired
    IPaymentManagerService paymentManagerService;

    /**
     * 订单退费
     * 只判断退费成功还是失败
     * @param requestVo
     * @return 成功：返回渠道退款单号 失败：失败原因
     */
    @RequestMapping(value = "/refund/create_order")
    public String refundOrder(@ModelAttribute VoReqRefund requestVo, BindingResult bindingResult) {
        TradeResultVo tradeResultVo = new TradeResultVo();

        _log.info("###### 开始接收商户统一退款请求 ######");
        try {
            //参数校验
            smartPayService.validateParams(requestVo,bindingResult);
            //调用服务
            VoResTradePayment payResultVo = paymentManagerService.refund(requestVo);
            //结果转换
            tradeResultVo.setRetCode(payResultVo.getRetCode());

            VoResRefund resPayCode = (VoResRefund) payResultVo.getRetData();
            tradeResultVo.setErrCode(resPayCode.getErrCode());
            tradeResultVo.setErrCodeDes(resPayCode.getErrCodeDes());

            if (PayConstant.TRADE_STATUS_SUCCESS.equalsIgnoreCase(payResultVo.getRetCode())){
                tradeResultVo.setMchId(resPayCode.getMchId());
                tradeResultVo.setMchOrderNo(resPayCode.getMchOrderNo());
                tradeResultVo.setChannelOrderNo(resPayCode.getChannelRefundNo());
                tradeResultVo.setMchRefundNo(resPayCode.getMchRefundNo());
                tradeResultVo.setChannelRefundNo(resPayCode.getChannelRefundNo());
            }
        } catch (Exception e) {
            e.printStackTrace();
            tradeResultVo.setRetCode(PayConstant.TRADE_STATUS_FAILED);
            tradeResultVo.setErrCode(PayConstant.TRADE_STATUS_SYSTEM_ERROR_CODE);
            tradeResultVo.setErrCodeDes("系统异常：" + e.getMessage());
            _log.error(PayConstant.TRADE_STATUS_SYSTEM_ERROR_DESC,e);
        }

        String result = JSON.toJSONString(tradeResultVo);
        _log.info("打印结果：" + result);

        return result;
    }
}
